package server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import plug.result.ReqPage;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.TenantDao;
import server.model.entity.Tenant;

import java.math.BigDecimal;
import java.util.Optional;
import java.util.UUID;

/**
 * @description:
 * @author: 许哲
 * @createTime: 2021/11/21 16:18
 * @version: 1.0
 */
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("v1/api/tenant")
public class TenantController {
    @Autowired
    private TenantDao tenantDao;

    @PostMapping("/all")
    public RetResult all(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        Tenant entity = JSON.parseObject(req.toJSONString(), Tenant.class);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Tenant> example = Example.of(entity, matcher);
        Page<Tenant> pages = tenantDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", pages.getContent(), (int) pages.getTotalElements());
    }

    @PostMapping("/save")
    public RetResult save(String name, String secretKey) {
        Tenant tenant = new Tenant();
        tenant.setCode(UUID.randomUUID().toString().replace("-", ""));
        tenant.setMoney(BigDecimal.ZERO);
        tenant.setName(name);
        tenant.setStatus(false);
        tenant.setSecretKey(secretKey);
        tenantDao.save(tenant);
        return RetResponse.makeOKRsp();
    }

    @PutMapping("/{uuid}/state")
    public RetResult state(@PathVariable String uuid) {
        Optional<Tenant> tenant = tenantDao.findById(uuid);
        if (tenant.isPresent()) {
            if(tenant.get().getStatus()){
                tenant.get().setStatus(false);
            }else{
                tenant.get().setStatus(true);
            }
            tenantDao.save(tenant.get());
        }
        return RetResponse.makeOKRsp();
    }
}
